package com.util;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;


public class GetIpAddr {

	final static Logger log = LoggerFactory.getLogger(GetIpAddr.class);

	/**
	 * 获取请求主机的IP地址
	 * @param request 请求
	 * @return
	 */
	public static String getIpAddr(HttpServletRequest request){
		String ip = "";
		try {
			ip = request.getHeader("x-forwarded-for");
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("Proxy-Client-IP");
			}
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("WL-Proxy-Client-IP");
			}
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getRemoteAddr();
			}
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip) || "127.0.0.1".equals(ip)) {
				if(request.getHeader("HTTP_VIA")!=null){
					ip = request.getHeader("HTTP_X_FORWARDED_FOR");
				}
			}
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip) || "127.0.0.1".equals(ip)) {
				if(request.getHeader("HTTP_VIA")!=null){
					ip = request.getHeader("REMOTE_ADDR");
				}
			}
		} catch (Exception e) {
			ip = "";
			e.printStackTrace();
		}
		return ip;
	}
	
}
